<?php
/**
 * Created by PhpStorm.
 * User: xaq
 * Date: 2017/5/20
 * Time: 20:55
 */

namespace app\api\controller\v1;

use app\api\controller\BaseController;
use app\api\validate\Count;
use app\api\validate\IDMustBePostiveInt;
use app\lib\exception\ProductException;
use think\Controller;
use app\api\model\Product as ProductModel;

class Product extends BaseController
{
    /**
     * @url /product/recent?count=3
     */
    public function getRecent($count=15){
        (new Count()) -> goCheck();
        $products = ProductModel::getMostRecent($count);
        if($products->isEmpty()) {
            throw new ProductException();
        }
        //临时隐藏summary字段，collection一组对象组成的对象
       // $collection = collection($products);  database.php设置返回的数据集为collection
        //$products = $products->hidden('summary');
        return $products;

    }

    /**
     * @url api/:version/product/by_category
     */
    public function getAllInCategory($id){
        (new IDMustBePostiveInt()) -> goCheck();
        $products = ProductModel::getProductsByCategoryID($id);
        if($products->isEmpty()) {
            throw new ProductException();
        }
        return $products;
    }

    /**
     * @url
     * @param $id  商品id
     * 获取商品的详情信息
     */
    public function getOne($id) {
        (new IDMustBePostiveInt()) ->goCheck();
        $product = ProductModel::getProductDetail($id);
        if(!$product){
            throw new ProductException();
        }
        return $product;
    }
}